const app = getApp()
Page({
  data: {
    ordercode:'',
    city:''
  },

  onLoad: function (options) {
    this.setData({ordercode:options.ordercode});
    this.setData({city:options.city});
    var that = this;
    that.getwxpayparms(options);
  },
  
  //根据 obj 的参数请求wx支付 
  requestPayment: function (obj) { 
    var that = this;
    var ordercode = obj.data.ordercode; 
    //定义小程序页面集合 
    var pages = getCurrentPages();
    //当前页面 (wxpay page) 
    var currPage = pages[pages.length - 1];
    //上一个页面 （index page）  
    var prevPage = pages[pages.length - 2]; 
    wx.requestPayment({ 
      'timeStamp': '' + obj.data.timestamp+'', 
      'nonceStr': '' + obj.data.noncestr+'',
      'package': ''+obj.data.package+'',
      'signType': 'MD5',
      'paySign': ''+obj.data.paysign+'', 
      'success': function (res) { 
          that.paystatecheck();
          prevPage.setData({ url: "https://dkcake.com/pay/orderdetail_mb.aspx?keycode=" + ordercode });
          wx.navigateBack(); 
        }, 
      'fail': function (res) { 
          prevPage.setData({ url: "https://dkcake.com/pay/orderdetail_mb.aspx?state=fail&keycode="+ordercode });
          wx.navigateBack(); 
        }
      })
    },
    //获得微信支付参数
    getwxpayparms: function (options){
      var that = this;
      wx.request({
        url: 'https://dkcake.com/action/weixinpayparms.ashx',
        data: { appid: app.globalData.appid, openid: options.openid, ordercode: options.ordercode,total_fee: options.total_fee, productlist: options.productlist },
        header: {},
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (res) {
          if (res.data.result) {
            that.requestPayment(res.data);
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false,
              success: function (res) {
                wx.navigateBack();
              }
            })
          }
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    },
    //支付状态验证
    paystatecheck:function(){
      wx.request({
        url: 'https://dkcake.com/action/xcxaction.ashx?action=paystatecheck',
        data: { ordercode:this.data.ordercode,city:this.data.city },
        header: {},
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    },
    
})